<?php

class Exts_Images {

	/**
	 * Get All images from directory
	 * @param string $directory
	 */
	public function getImgsByDirectory($directory) {
		if ($handle = opendir($directory)) {
			$files = array();
			while (false !== ($file = readdir($handle))) {
				if ($file == '..' || $file == '.' || $file =='.htaccess') {
					continue;
				}
				$files[] = $file;
			}
			closedir($handle);
		}
		return $files;
	}

	/**
	 * Return a destination path, from source and the resolution
	 * @param string $source
	 * @param string $resolution
	 * @return string $destination
	 */
	public function getDestination($source, $resolution) {
		$res = array();
		preg_match("/(.*)\./", $source, $res);
		$destination = $res[1] . '_'
			. str_replace("x", "_", $resolution) . '.jpg';
		return $destination;
	}

	public function resize($source, $destination, $resolution) {

		if (file_exists($source)) {
			if ($resolution != false) {
				if (file_exists($destination)) {

					return TRUE;
				}
				if (strlen($resolution) > 9
					|| strlen($resolution) < 3
					|| !strpos($resolution, 'x')) {
					throw new Exts_Exception("You need especificate a valid
						Resolution for the new image.");
				}

				exec("convert $source -resize $resolution $destination ");
				return true;
			} else {
				throw new Exts_Exception("You need especificate a Resolution for the
					new image.");
			}
		} else {
			throw new Exts_Exception(
				"<br/>The image '{$source}' dosen't exists.<br/>"
			);
		}
	}

}